package com.redis.demo.service;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.stream.ReadOffset;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StreamOperations;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author 郭承乐
 * @Date 9:34 2024/8/22
 **/
@Service
@RequiredArgsConstructor
public class MessageProducer {
    private final RedisTemplate<String, String> redisTemplate;

    @PostConstruct
    public void initializeStream() {
        StreamOperations<String, Object, Object> streamOperations = redisTemplate.opsForStream();
        // 创建一个流
        try {
            streamOperations.createGroup("your-stream-name", ReadOffset.from("0"), "your-consumer-group");
        } catch (Exception e) {
            // 流可能已存在，忽略异常
        }
    }

    public void sendMessage( String messageKey, String message) {
        Map<String, String> messageMap = new HashMap<>();
        String streamKey = "your-stream-name";
        messageMap.put(messageKey, message);
        RecordId recordId = redisTemplate.opsForStream().add(streamKey, messageMap);
        if (recordId != null) {
            System.out.println("Message sent to Stream '" + streamKey + "' with RecordId: " + recordId);
        }
    }
}